<template>
  <Top-Page class="square-box">
    <NavBar title="直播广场" left-arrow @click-left="navBack()" />

    <view v-if="playerShow" class="H5-live" id="player_bridging" ref="refH5Live"></view>

    <view class="list">
      <view class="list-item" v-for="item in list" @click="inRoom(item)">
        <view class="room-info">
          <view class="channel-id">房间号:{{ item.channel_id }}</view>
          <image class="cover-img" :src="item.coverImg" mode="aspectFill" />
        </view>

        <view class="publisher-info">
          <image class="publisher__table" :src="item.avatar" mode="aspectFill" />
          <view class="publisher__value">{{ item.publisher }}</view>
        </view>
      </view>
    </view>

    <view v-if="emptyShow" class="empty">当前暂无直播</view>
  </Top-Page>
</template>

<script>
// #ifdef APP
var playModule = uni.requireNativePlugin('PLV-LiveUniPlugin-WatchPlayModule');
var configModule = uni.requireNativePlugin('PLV-LiveUniPlugin-WatchConfigModule');
// #endif

// #ifndef APP
// import { createWatchCore, PolyvWatchCoreEvents } from '@polyv/live-watch-sdk';
// #endif
import NavBar from '@/components/NavBar/NavBar.vue';
import { navBack } from '@/utils/utils.js';
export default {
  data() {
    return {
      navBack,
      emptyShow: false,
      playerShow: false,
      list: [],
      userInfo: uni.getStorageSync('userInfo'),
      watchCore: null
    };
  },
  components: { NavBar },
  created() {
    this.firstApi();
  },
  mounted() {
    // #ifdef APP
    //配置观众信息
    this.setViewerInfo();

    //配置跑马灯信息
    this.setMarqueeConfig();

    //设置iPad全屏配置
    this.setFullScreenButtonShow();
    // #endif

    // #ifndef APP
    this.watchCore.chat.eventEmitter.on(ChatEvents.ChatUserLogout, (data) => {
      const userId = data.userId;
      console.log('退出的用户 id', userId);
      if (userId == this.userInfo.user_id) {
        this.firstApi();
      }
    });
    // #endif
  },
  methods: {
    firstApi() {
      this.playerShow = false;
      this.list.length = 0;

      this.$api.msgApi
        .liveData()
        .then((res) => {
          if (res.code != 0) {
            uni.showToast({
              title: `${res.msg}`,
              icon: 'none'
            });
          }

          const { data } = res;

          this.list.push(...data);

          this.emptyShow = data.length ? false : true;
        })
        .catch((err) => {
          uni.showToast({
            title: `${err}`
          });
          this.emptyShow = true;
        });
    },
    inRoom(item) {
      // #ifdef APP
      this.setUserInfo(item);
      // #endif

      // #ifndef APP
      this.playerShow = true;

      setTimeout(() => {
        this.H5LiveInit(item);
      }, 500);
      // #endif
    },
    async H5LiveInit(item) {
      this.watchCore = createWatchCore({
        channelId: item.channel_id, // 传入观看页的频道号
        userInfo: {
          userId: item.imUserID,
          nick: item.realname,
          pic: decodeURIComponent(item.avatar),
          actor: ''
        }
      });

      // 安装核心实例
      await this.watchCore.setup();

      // 互动 SDK
      this.watchCore.interactReceive.setupIarCore();

      const supportResult = this.watchCore.player.supportLowLatency();
      let lowLatency = true;
      if (supportResult.support) {
        lowLatency = true;
      } else {
        lowLatency = false;
      }

      //播放器 SDK
      await this.watchCore.player.setupPlayer({
        container: this.$refs.refH5Live.$el,
        lowLatency: lowLatency, // 使用无延迟播放
        autoChangePlayback: false,
        autoplay: true,
        barrageEnabled: true,
        showController: true,
        fullScreenMode: true
      });

      this.watchCore.player.bindSocketEvents();

      // 连接聊天室进入直播观看页
      await this.watchCore.connect();
    },
    setViewerInfo() {
      configModule.setViewerInfo(
        {
          viewerId: this.userInfo.user_id,
          viewerName: this.userInfo.realname,
          viewerAvatar: this.userInfo.avatar
        },
        (result) => {
          // uni.showToast({
          // 	title: result.isSuccess ? 'setViewerInfo succeed' : result.errMsg,
          // 	icon: 'none'
          // });
        }
      );
    },
    //配置跑马灯信息
    setMarqueeConfig() {
      configModule.setMarqueeConfig(
        {
          code: ''
        },
        (result) => {
          // title: result.isSuccess ? 'setMarqueeConfig succeed' : result.errMsg,

          !result.isSuccess &&
            uni.showToast({
              title: result.errMsg,
              icon: 'none'
            });
        }
      );
    },
    // 设置iPad 上是否显示全屏按钮（仅在iPad上生效）
    setFullScreenButtonShow() {
      let platform = uni.getSystemInfoSync().platform;
      if (platform == 'ios') {
        playModule.showFullScreenButtonOnIPad({
          show: true
        });
      }
    },
    // 设置多场景的账号属性
    setUserInfo(item) {
      uni.showToast({
        title: '登陆中...',
        icon: 'loading',
        mask: true,
        duration: 999999
      });

      var that = this;
      configModule.setConfig(
        {
          appId: decodeURIComponent(item.appId),
          userId: decodeURIComponent(item.userId),
          appSecret: decodeURIComponent(item.appSecret)
        },
        (result) => {
          if (result.isSuccess) {
            that.startLive(item);
          } else {
            uni.showToast({
              title: result.errMsg,
              icon: 'none'
            });
          }
        }
      );
    },
    startLive(item) {
      const playType = item.playType ?? 0;
      if (playType === 0) {
        // 直播
        playModule.loginLiveRoom(
          this.sceneType,
          {
            channelId: item.channel_id
          },
          (result) => {
            uni.hideToast();
            // title: result.isSuccess ? 'login succeed' : result.errMsg,
            !result.isSuccess &&
              uni.showToast({
                title: result.errMsg,
                icon: 'none'
              });
          }
        );
      } else if (playType === 1) {
        // 回放
        playModule.loginPlaybackRoom(
          this.sceneType,
          {
            channelId: item.channel_id,
            videoId: item.playbackInfo.vid,
            vodType: item.isVideoList
          },
          (result) => {
            uni.hideToast();
            // title: result.isSuccess ? 'login succeed' : result.errMsg,
            !result.isSuccess &&
              uni.showToast({
                title: result.errMsg,
                icon: 'none'
              });
          }
        );
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
